#include<iostream>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<string>
#include<cstring>

// ./tcplient sever_ip sever_port

int main(int argc, char *argv[])
{
    if (argc != 3) // 参数个数
    {
        std::cerr << "Usage: " << argv[0] << "sever_ip sever_port" << std::endl;
        exit(0);
    }
    //1.创建套接字
    std::string severip = argv[1];
    uint16_t severport = std::atoi(argv[2]);
    int sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0)
    {
        std::cerr << "client create socket error" << std::endl;
        exit(0);
    }

    //2.客户端不需要显示bind os会自动bind ip 和随机端口号
    struct sockaddr_in sever;
    memset(&sever, 0, sizeof(sever));
    sever.sin_family = AF_INET;
    sever.sin_port = htons(severport);
    //sever.sin_addr.s_addr 字符串风格ip地址到网络序列
    ::inet_pton(AF_INET, severip.c_str(), &sever.sin_addr);

    int n = ::connect(sockfd, (const struct sockaddr*)&sever, sizeof(sever));
    if(n < 0)
    {
        std::cerr << "client connect socket error" << std::endl;
        exit(0);
    }

    while(true)
    {
        std::string message;
        std::cout << "Enter #:";
        std::getline(std::cin, message);

        ::write(sockfd, message.c_str(), message.size());
        char echo_buffer[1024];
        int n = ::read(sockfd, echo_buffer, sizeof(echo_buffer));
        if(n > 0)
        {
            echo_buffer[n] = 0;
            std::cout << echo_buffer << std::endl;
        }
        else
        {
            break;
        }
    }

    return 0;
}